package com.suiwei.elasticJob.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.suiwei.elasticJob.model.FileCustom;import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
 * @author suiwei
 * @date 2023/12/20 16:44
 */
@Component
public class FileBackupJob implements SimpleJob {
  private final int FETCH_SIZE = 1;
  public static List<FileCustom> files = new ArrayList<>();
  static {
    for(int i=1;i<11;i++){
      FileBackupJob.files.add(new FileCustom(String.valueOf(i+10),"文件"+(i+10),"text","content"+ (i+10)));
      FileBackupJob.files.add(new FileCustom(String.valueOf(i+20),"文件"+(i+20),"image","content"+ (i+20)));
      FileBackupJob.files.add(new FileCustom(String.valueOf(i+30),"文件"+(i+30),"radio","content"+ (i+30)));
      FileBackupJob.files.add(new FileCustom(String.valueOf(i+40),"文件"+(i+40),"video","content"+ (i+40)));
    }
    System.out.println("生产测试数据完成");
  }

  @Override
  public void execute(ShardingContext shardingContext) {
    System.out.println("作业分片"+shardingContext.getShardingItem());
    // 获取未备份的文件
    List<FileCustom> fileCustoms = fetchUnBackupFiles(FETCH_SIZE);
    // 进行文件备份
    backupFiles(fileCustoms);
  }

  public List<FileCustom> fetchUnBackupFiles(int count) {
    List<FileCustom> fetchFile = new ArrayList<>();
    int num = 0;
    for (FileCustom file : files) {
      if (num >= count) {
        break;
      }
      if (!file.getBackup()) {
        fetchFile.add(file);
        num++;
      }
    }
      System.out.printf("time:%s,获取文件%d个\n", LocalDateTime.now(),num);
    return fetchFile;
  }

  public void backupFiles(List<FileCustom> fetchFile) {
    for (FileCustom file : fetchFile) {
      file.setBackup(true);
      System.out.printf(
          "time:%s,备份文件，名称：%s，类型：%s\n", LocalDateTime.now(), file.getName(), file.getType());
    }
  }
}
